<?php
declare (strict_types=1);
namespace app\admin\controller;
use app\admin\model\User as UserModel;
use app\admin\validate\LoginUser;
use app\tool\Controller\StrController;
use app\tool\Controller\CacheController;
use app\BaseController;
use app\tool\controller\TokenController;
use think\facade\Config;
use think\Request;
class LoginController extends BaseController
{
    /**
     * 登录页面
     *
     * @return \think\Response
     */
    public function login()
    {
        $validate = new LoginUser();
        $result = $validate->check($this->getData);
        if (!$result) {
            return $this->error($validate->getError());
        }
        $userDetail = UserModel::findByPassWord(StrController::encode($this->getData['pass_word'], Config::get('app.str_key')));
        if ($userDetail) {
            $token = TokenController::createToken($userDetail);
            $openidToken = CacheController::set('user_' . $userDetail['id'], $token['token'], Config::get('app.token_exp_time'));
            CacheController::set($token['token'], $userDetail, Config::get('app.token_exp_time'));
            return $this->success('登录成功', ['token' => $token]);
        } else {
            return $this->error('用户不存在');
        }
    }
    /*
     * 退出页面
     *
    */
    public function loginOut()
    {
        $user = $this->user;
        $token = $this->request->header('token'); // 假设token是通过Authorization头部发送的
        $delUser = CacheController::delete('user_' . $user['id']);
        $delToken = CacheController::delete($token);
        return $this->success('退出成功');
    }
}
